package org.mspring.mlog.web.blog;

import org.mspring.mlog.common.ArticleDto;
import org.mspring.mlog.entity.ArticleEntity;
import org.mspring.mlog.common.constants.ArticleStatus;
import org.mspring.mlog.service.ArticleEntityService;
import org.mspring.mlog.support.ServiceContext;
import org.mspring.nbee.common.PageResult;
import org.mspring.nbee.db.dao.sql.builder.part.condition.Operator;
import org.mspring.nbee.db.dao.sql.builder.part.condition.SqlCondition;
import org.mspring.nbee.db.dao.sql.builder.part.condition.impl.SimpleCondition;
import org.mspring.nbee.db.dao.sql.pager.OrderType;
import org.mspring.nbee.db.dao.sql.pager.SqlPager;
import org.mspring.nbee.web.support.QueryParam;
import org.mspring.nbee.web.support.WebContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

/**
 * @author Gao Youbo
 * @since 2016-01-09 20:31
 */
@Controller("blogIndexController")
public class IndexController {
    private ArticleEntityService articleEntityService;
    private ServiceContext serviceContext;

    @RequestMapping({"/index", "/", ""})
    public String index(WebContext context, Model model) {
        SqlPager pager = context.getPager();
        pager.addOrder("id", OrderType.DESC);
        List<SqlCondition> conditions = context.buildSqlConditions(model,
                new QueryParam(ArticleEntity.Fields.title, Operator.LIKE),
                new QueryParam(ArticleEntity.Fields.category, Operator.EQ)
        );
        conditions.add(new SimpleCondition("status", Operator.EQ, ArticleStatus.NORMAL));
        PageResult<ArticleEntity> tempResult = articleEntityService.list(conditions, pager);
        PageResult<ArticleDto> articleResult = new PageResult<>();
        articleResult.setPager(tempResult.getPager());
        articleResult.setTotal(tempResult.getTotal());
        articleResult.setItemList(ArticleDto.fromArticles(tempResult.getItemList(), serviceContext));
        model.addAttribute("articleResult", articleResult);
        return "/blog/index";
    }

    @Autowired
    public void setArticleEntityService(ArticleEntityService articleEntityService) {
        this.articleEntityService = articleEntityService;
    }

    @Autowired
    public void setServiceContext(ServiceContext serviceContext) {
        this.serviceContext = serviceContext;
    }
}
